import React, { useEffect, useState, useMemo } from 'react';
import {useNavigate} from "react-router-dom";
import {Row, Col, Progress, Tooltip} from 'antd'
import 'echarts-gl'
import moment from "moment";
import AMapLoader from '@amap/amap-jsapi-loader';
import {Get, Url} from "../../server/http";
import { getVolumeByMB, getVolume, cpy } from "../../utils/cmn";
import Header from './Header'
import Title from '../Screen/Title'
import OverviewCard from '../Screen/OverviewCard'
import ItemCard from '../Screen/ItemCard'
import Histogram from '../../component/Histogram'
import PieChart from '../../component/PieChart'
import chinaJson from '../../utils/cities/dianjun_sub.json'

import './index.less'
import dianjunjie from "../../utils/cities/dianjunjie.json";
import aijia from "../../utils/cities/aijiazhen.json";
import qiaobian from "../../utils/cities/qiaobianzhen.json";
import lianpeng from "../../utils/cities/lianpengxiang.json";
import tucheng from "../../utils/cities/tuchengxiang.json";


const mapKey = '3d944fa68cc341b006493f43d96bb16a';

const townList = {
	'点军街道': {lng: 111.28546780, lat: 30.73362632},
	'艾家镇': {lng: 111.32806270, lat: 30.61390956},
	'桥边镇': {lng: 111.19969975, lat: 30.74026338},
	'土城乡': {lng: 111.11365619, lat: 30.69358401},
	'联棚乡': {lng: 111.25029983, lat: 30.64412036},
}
let mapObj = null;  // AMap对象
let map = null;     // 创建的地图实例

const Allowance = () => {
	const navigate = useNavigate();
	const [subsidyData, setSubsidy] = useState([]);     // 补贴统计信息
	const [doubtSubsidyData, setDoubtSubsidy] = useState([]);     // 疑点补贴统计信息
	const [townSubsidyData, setTownSubsidy] = useState([]);     // 按乡镇统计补贴
	const [townDoubtSubsidyData, setTownDoubtSubsidy] = useState([]);     // 按乡镇统计疑点补贴
	const [subsidySort, setSubsidySort] = useState([]);     // 补贴人数排序
	const [doubtSubsidySort, setDoubtSubsidySort] = useState([]);     // 补贴人数排序

	useEffect(() => {
		getSubsidy();
		getDoubtSubsidy();
		getTownshipSubsidy();
		getSubsidySort();
		getDoubtSubsidySort();
		initMap()

		return () => {
			mapObj = null;  // AMap对象
			map = null;     // 创建的地图实例
		}
	}, [])

	// 初始化地图
	const initMap = () => {
		AMapLoader.load({
			"key": mapKey,              // 申请好的Web端开发者Key，首次调用 load 时必填
			"version": "2.0",   // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
			"plugins": ['AMap.GeoJSON'],           // 需要使用的的插件列表，如比例尺'AMap.Scale'等
			"AMapUI": {             // 是否加载 AMapUI，缺省不加载
				"version": '1.1',   // AMapUI 缺省 1.1
				"plugins":[],       // 需要加载的 AMapUI ui插件
			},
			"Loca":{                // 是否加载 Loca， 缺省不加载
				"version": '2.0.0'  // Loca 版本，缺省 1.3.2
			},
		}).then((AMap)=>{
			mapObj = AMap;
		}).catch(e => {
			console.log(e);
		})
	}

	// 创建地图
	const creatMap = (data) => {
		console.log('data', data);
		map = new mapObj.Map('china-map', {
			zoom: 11,
			resizeEnable: true,
			pitch: 45,
			center: [111.169233, 30.662411],
			showBuildingBlock: true,
			showLabel: false,
			zoomEnable: false,   //是否缩放
			dragEnable: false,  //是否拖动
			mapStyle: "amap://styles/7049faf9a31244784b3c15dcf5c1f30d",
		});

		let dianjunGeo = new mapObj.GeoJSON({
			geoJSON: dianjunjie,
			// 还可以自定义getMarker和getPolyline
			getPolygon: function(geojson, lnglats) {
				return new mapObj.Polygon({
					path: lnglats,
					strokeColor: 'gray',
					fillColor: '#514dc7'
				});
			}
		});
		let aijiaGeo = new mapObj.GeoJSON({
			geoJSON: aijia,
			// 还可以自定义getMarker和getPolyline
			getPolygon: function(geojson, lnglats) {
				return new mapObj.Polygon({
					path: lnglats,
					strokeColor: 'gray',
					fillColor: '#314dc7'
				});
			}
		});
		let qiaobianGeo = new mapObj.GeoJSON({
			geoJSON: qiaobian,
			// 还可以自定义getMarker和getPolyline
			getPolygon: function(geojson, lnglats) {
				return new mapObj.Polygon({
					path: lnglats,
					strokeColor: 'gray',
					fillColor: '#814dc7'
				});
			}
		});
		let lianpengGeo = new mapObj.GeoJSON({
			geoJSON: lianpeng,
			// 还可以自定义getMarker和getPolyline
			getPolygon: function(geojson, lnglats) {
				return new mapObj.Polygon({
					path: lnglats,
					strokeColor: 'gray',
					fillColor: '#114dc7'
				});
			}
		});
		let tuchengGeo = new mapObj.GeoJSON({
			geoJSON: tucheng,
			// 还可以自定义getMarker和getPolyline
			getPolygon: function(geojson, lnglats) {
				return new mapObj.Polygon({
					path: lnglats,
					strokeColor: 'gray',
					fillColor: '#b14dc7'
				});
			}
		});
		dianjunGeo.on('mouseover', ()=>openWindow({lng: townList['点军街道']['lng'],lat: townList['点军街道']['lat'], title: '点军街道'}, data['点军街道'] || {}))
		dianjunGeo.on('mouseout', closeWindow)
		aijiaGeo.on('mouseover', ()=>openWindow({lng: townList['艾家镇']['lng'],lat: townList['艾家镇']['lat'], title: '艾家镇'}, data['艾家镇'] || {}))
		aijiaGeo.on('mouseout', closeWindow)
		qiaobianGeo.on('mouseover', ()=>openWindow({lng: townList['桥边镇']['lng'],lat: townList['桥边镇']['lat'], title: '桥边镇'}, data['桥边镇'] || {}))
		qiaobianGeo.on('mouseout', closeWindow)
		lianpengGeo.on('mouseover', ()=>openWindow({lng: townList['联棚乡']['lng'],lat: townList['联棚乡']['lat'], title: '联棚乡'}, data['联棚乡'] || {}))
		lianpengGeo.on('mouseout', closeWindow)
		tuchengGeo.on('mouseover', ()=>openWindow({lng: townList['土城乡']['lng'],lat: townList['土城乡']['lat'], title: '土城乡'}, data['土城乡'] || {}))
		tuchengGeo.on('mouseout', closeWindow)

		map.add(dianjunGeo);
		map.add(aijiaGeo);
		map.add(qiaobianGeo);
		map.add(lianpengGeo);
		map.add(tuchengGeo);
	}

	// 关闭区域信息窗口
	const closeWindow = () => {
		map.clearInfoWindow();
	}

	// 打开区域信息窗口
	const openWindow = (data, info) => {
		console.log('info', info);
		if (mapObj === null || map === null) {
			return ;
		}
		if (!data || !data['lng'] || !data['lat'])  {
			return ;
		}
		map.clearInfoWindow();
		let content = [];
		content.push(`<div style="font-size:16px;color:white;margin-left: 10px;height: 10px;">${data['title']}</div>`);
		content.push(`<span style="font-size:13px;color:white;margin-left: 10px;">补贴总额&nbsp;&nbsp;${info['subsidy'] || '-'}元</span>`);
		content.push(`<span style="font-size:13px;color:white;margin-left: 10px;">补贴总人数&nbsp;&nbsp;${info['people'] || '-'}</span>`);
		content.push(`<span style="font-size:13px;color:white;margin-left: 10px;">疑点补贴总额&nbsp;&nbsp;${info['doubt'] || '-'}元</span>`);
		let infoWindow = new mapObj.InfoWindow({
			isCustom: true,  //使用自定义窗体
			content: createInfoWindow(content.join("<br/>")),
			offset: new mapObj.Pixel(20, 0),
		});
		infoWindow.open(map, new mapObj.LngLat(data['lng'], data['lat']));
	}

	// 创建窗体
	const createInfoWindow = (content) => {
		let info = document.createElement("div");
		info.className = "content-window-card";

		//可以通过下面的方式修改自定义窗体的宽高
		info.style.width = "250px";
		info.style.height = "150px";
		// 定义中部内容
		let middle = document.createElement("div");
		middle.className = "info-middle";
		middle.innerHTML = content;
		info.appendChild(middle);

		return info;
	}

	// 按类别统计补贴数据
	const getSubsidy = () => {
		Get(Url.SUBSIDY_STATISTIC,).then(
			data => {
				if (data?.status === 'success') {
					let list = data?.data
					let temp = [
						{name: '生态', value: Math.floor(list['ecological']) || 0},
						{name: '高龄', value: Math.floor(list['elderly']) || 0},
						{name: '耕地', value: Math.floor(list['farmland']) || 0},
						{name: '移民', value: Math.floor(list['immigration']) || 0},
						{name: '就业', value: Math.floor(list['employment']) || 0},
						{name: '灵活就业', value: Math.floor(list['flex_employment']) || 0},
						{name: '实习', value: Math.floor(list['intership']) || 0},
					]
					setSubsidy(temp)
				}
			}
		)
	}
	// 按类别统计违规补贴数据
	const getDoubtSubsidy = () => {
		Get(Url.DOUBT_SUBSIDY_STATISTIC,).then(
			data => {
				if (data?.status === 'success') {
					let list = data?.data
					let temp = [
						{name: '生态', value: Math.floor(list['ecological']) || 0},
						{name: '高龄', value: Math.floor(list['elderly']) || 0},
						{name: '耕地', value: Math.floor(list['farmland']) || 0},
						{name: '实习', value: Math.floor(list['intership']) || 0},
					]
					setDoubtSubsidy(temp)
				}
			}
		)
	}

	// 按乡镇统计补贴数据
	const getTownshipSubsidy = () => {
		Get(Url.TOWNSHIP_SUBSIDY_STATISTIC,).then(
			data => {
				if (data?.status === 'success') {
					let list = data?.data
					const arr = {'点军': '点军街道', '桥边': '桥边镇', "艾家": "艾家镇", "土城": "土城乡", "联棚": "联棚乡"}
					let townTemp = {
						'点军街道': {subsidy: 0, doubt: 0, people: 0},
						'艾家镇': {subsidy: 0, doubt: 0, people: 0},
						'桥边镇': {subsidy: 0, doubt: 0, people: 0},
						'土城乡': {subsidy: 0, doubt: 0, people: 0},
						'联棚乡': {subsidy: 0, doubt: 0, people: 0},
					}
					let info = []
					for (let k in list) {
						let temp = 0
						for (let m in list[k]) {
							if (list[k][m]) {
								for (let n in list[k][m]) {
									if (list[k][m][n]) {
										temp += list[k][m][n]
									}
								}
							}
							info.push({name: arr[m], value: temp})
							list[k][m] = Math.floor(temp)
							townTemp[arr[m]]['subsidy'] = temp
						}
					}
					setTownSubsidy(info)
					getTownshipDoubtSubsidy(townTemp);
				}
			}
		)
	}
	// 按乡镇统计违规补贴数据
	const getTownshipDoubtSubsidy = (townTemp) => {
		Get(Url.TOWNSHIP_DOUBT_SUBSIDY_STATISTIC,).then(
			data => {
				if (data?.status === 'success') {
					let list = data?.data
					const arr = {'点军': '点军街道', '桥边': '桥边镇', "艾家": "艾家镇", "土城": "土城乡", "联棚": "联棚乡"}
					let info = []
					for (let k in list) {
						let temp = 0
						for (let m in list[k]) {
							if (list[k][m]) {
								for (let n in list[k][m]) {
									if (list[k][m][n]) {
										temp += list[k][m][n]
									}
								}
							}
							info.push({name: arr[m], value: temp})
							list[k][m] = Math.floor(temp)
							townTemp[arr[m]]['doubt'] = temp
						}
					}
					setTownDoubtSubsidy(info)

					getTownData(townTemp);
				}
			}
		)
	}

	// 补贴人数排序
	const getSubsidySort = () => {
		Get(Url.SUBSIDY_SORT,).then(
			data => {
				if (data?.status === 'success') {
					let temp = []
					const arr = {
						elderly: '高龄', immigration: '移民', flex_employment: "灵活就业",
						farmland: "耕地", ecological: "生态", intership: '实习',
						employment: "就业", student: '学生就业'
					}
					temp = data?.data.reverse();
					for (let k in temp) {
						temp[k]['name'] = arr[temp[k]['key']]
					}
					setSubsidySort(temp)
				}
			}
		)
	}
	// 疑点补贴人数排序
	const getDoubtSubsidySort = () => {
		Get(Url.DOUBT_SUBSIDY_SORT,).then(
			data => {
				if (data.length>0) {
					let temp = []
					const arr = {
						elderly: '高龄', immigration: '移民', flex_employment: "灵活就业",
						farmland: "耕地", ecological: "生态", intership: '实习',
						employment: "就业", student: '学生就业'
					}
					temp = data.reverse();
					for (let k in temp) {
						temp[k]['name'] = arr[temp[k]['key']]
					}
					setDoubtSubsidySort(temp)
				}
			}
		)
	}

	// 获取各乡镇人数
	const getTownData = (townTemp) => {
		Get(Url.TOWN_PEOPLE,).then(
			data => {
				if (data?.status === 'success') {
					let list = data?.data
					const arr = {'点军': '点军街道', '桥边': '桥边镇', "艾家": "艾家镇", "土城": "土城乡", "联棚": "联棚乡"}
					let info = []
					for (let k in list) {
						let temp = 0
						for (let m in list[k]) {
							if (list[k][m]) {
								for (let n in list[k][m]) {
									if (list[k][m][n]) {
										temp += list[k][m][n]
									}
								}
							}
							info.push({name: arr[m], value: temp})
							list[k][m] = Math.floor(temp)
							townTemp[arr[m]]['people'] = temp
						}
					}
					creatMap(townTemp);
				}
			}
		)
	}


	return (
		<div className={'full-screen'}>
			<Header />
			<div className={'map-warp'}>
				<div id={'china-map'} className={'chinaMap'}/>
			</div>
			<div className={'suspended-layer-left'}>
				<Row style={{width: '100%', height: '60vh', marginTop: '1vh'}}>
					<ItemCard >
						<div style={{paddingTop: '1vh'}}>
							<Row type={'flex'}><Title title={'补贴金额情况'}/></Row>
							<Row type={'flex'}>
								<Col span={12} style={{height: '26vh', padding: '0.5vh'}}>
									<Row type={'flex'} justify={'center'} style={{color: 'white'}}>各乡镇补贴</Row>
									<div style={{width: '100%', height: '24vh'}}>
										<Histogram data={townSubsidyData}/>
									</div>
								</Col>
								<Col span={12}>
									<Row type={'flex'} justify={'center'} style={{color: 'white'}}>乡镇补贴占比</Row>
									<div style={{width: '100%', height: '24vh'}}>
										<PieChart id={'subsidy-1'} data={townSubsidyData} title={'补贴(元)'}/>
									</div>
								</Col>
							</Row>
							<Row type={'flex'} style={{marginTop: '1vh'}}>
								<Col span={12} style={{height: '26vh', padding: '0.5vh'}}>
									<Row type={'flex'} justify={'center'} style={{color: 'white'}}>各类别补贴</Row>
									<div style={{width: '100%', height: '24vh'}}>
										<Histogram data={subsidyData}/>
									</div>
								</Col>
								<Col span={12} style={{height: '26vh', padding: '0.5vh'}}>
									<Row type={'flex'} justify={'center'} style={{color: 'white'}}>类别补贴占比</Row>
									<div style={{width: '100%', height: '24vh'}}>
										<PieChart id={'subsidy-2'} data={subsidyData} title={'补贴(元)'}/>
									</div>
								</Col>
							</Row>
						</div>
					</ItemCard>
				</Row>
				<Row style={{width: '100%', height: '28vh', marginTop: '1vh'}}>
					<ItemCard>
						<div style={{paddingTop: '1vh'}}>
							<Row type={'flex'}><Title title={'补贴人数TOP'}/></Row>
							<div style={{width: '98%'}}>
								{
									subsidySort.map((item) => (
										<Row type={'flex'} style={{marginTop: '0.5vh', height: '2vh'}}>
											<Col span={4}>
												<Row type={'flex'} justify={'end'} style={{color: 'white', fontSize: '1.4vh'}}>
													{item['name']}：
												</Row>
											</Col>
											<Col span={18}>
												<Tooltip placement="top" title={item['value']+' 人'}>
													<div
														style={{
															height: '100%',
															width: item['value']/subsidySort[0]['value']*100+'%',
															backgroundColor: 'whitesmoke'
														}}
													/>
												</Tooltip>
											</Col>
										</Row>
									))
								}
							</div>
						</div>
					</ItemCard>
				</Row>
			</div>
			<div className={'suspended-layer-right'}>
				<Row style={{width: '100%', height: '60vh', marginTop: '1vh'}}>
					<ItemCard >
						<div style={{paddingTop: '1vh'}}>
							<Row type={'flex'}><Title title={'疑点补贴金额情况'}/></Row>
							<Row type={'flex'}>
								<Col span={12}>
									<Row type={'flex'} justify={'center'} style={{color: 'white'}}>各乡镇疑点补贴</Row>
									<div style={{width: '100%', height: '24vh'}}>
										<Histogram data={townDoubtSubsidyData}/>
									</div>
								</Col>
								<Col span={12}>
									<Row type={'flex'} justify={'center'} style={{color: 'white'}}>乡镇疑点补贴占比</Row>
									<div style={{width: '100%', height: '24vh'}}>
										<PieChart id={'subsidy-3'} data={townDoubtSubsidyData} title={'补贴(元)'}/>
									</div>
								</Col>
							</Row>
							<Row type={'flex'} style={{marginTop: '1vh'}}>
								<Col span={12} style={{height: '26vh', padding: '0.5vh'}}>
									<Row type={'flex'} justify={'center'} style={{color: 'white'}}>各类别疑点补贴</Row>
									<div style={{width: '100%', height: '24vh'}}>
										<Histogram data={doubtSubsidyData}/>
									</div>
								</Col>
								<Col span={12}>
									<Row type={'flex'} justify={'center'} style={{color: 'white'}}>类别疑点补贴占比</Row>
									<div style={{width: '100%', height: '24vh'}}>
										<PieChart id={'subsidy-4'} data={doubtSubsidyData} title={'补贴(元)'}/>
									</div>
								</Col>
							</Row>
						</div>
					</ItemCard>
				</Row>
				<Row style={{width: '100%', height: '28vh', marginTop: '1vh'}}>
					<ItemCard>
						<div style={{paddingTop: '1vh'}}>
							<Row type={'flex'}><Title title={'疑点补贴人数TOP'}/></Row>
							<div style={{width: '98%'}}>
								{
									doubtSubsidySort.map((item) => (
										<Row type={'flex'} style={{marginTop: '0.5vh', height: '2vh'}}>
											<Col span={4}>
												<Row type={'flex'} justify={'end'} style={{color: 'white', fontSize: '1.4vh'}}>
													{item['name']}：
												</Row>
											</Col>
											<Col span={18}>
												<Tooltip placement="top" title={item['value']+' 人'}>
													<div
														style={{
															height: '100%',
															width: item['value']/doubtSubsidySort[0]['value']*100+'%',
															backgroundColor: 'whitesmoke'
														}}
													/>
												</Tooltip>
											</Col>
										</Row>
									))
								}
							</div>
						</div>
					</ItemCard>
				</Row>
			</div>
		</div>
	);
};

export default Allowance;
